package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.ApplicationContextRegister;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.CookieUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.haojiangboutils.MenuVueUtils;
import com.bootdo.haojiangboutils.ResultReBuild;
import com.bootdo.newmenu.MenuModel;
import com.bootdo.redis.RedisUtil;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MenuService;


import com.bootdo.system.service.UserService;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@Autowired
	RedisUtil redisUtil;

	@Autowired
	UserService userService;
	@GetMapping({ "/", "" })
	String welcome(Model model) {
		return "redirect:/index";
	}

	@Log("请求访问主页")
	@GetMapping({ "/index" })
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if(fileDO!=null&&fileDO.getUrl()!=null){
			if(fileService.isExist(fileDO.getUrl())){
				model.addAttribute("picUrl",fileDO.getUrl());
			}else {
				model.addAttribute("picUrl","/img/photo_s.jpg");
			}
		}else {
			model.addAttribute("picUrl","/img/photo_s.jpg");
		}
		model.addAttribute("username", getUser().getUsername());
		return "index_v1";
	}

	@GetMapping("/login")
	String login(HttpServletRequest request) {	
		Subject subject = SecurityUtils.getSubject();
		String username =  CookieUtils.getCookie("saveMe", request);
		if(!StringUtils.isEmpty(username)){
			Map<String, Object> map = new HashMap<>(16);
			map.put("username", username);
			UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
			// 查询用户信息
			UserDO user = userMapper.list(map).get(0);
			if(null != user){
				UsernamePasswordToken token = new UsernamePasswordToken(username, user.getPassword());
				subject.login(token);
			}
		}
		if(subject.isAuthenticated()){
			return "redirect:/index";
		}else{
			return "login";
		}
	}

	@Log("登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String username, String password, HttpServletRequest request,HttpServletResponse response) {
		String saveMe =  request.getParameter("saveMe");
		if("on".equals(saveMe)){
			CookieUtils.setCookie("saveMe", username, response, 60*60*24*30);
		}	
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			String tokenKey = UUID.randomUUID().toString();
			redisUtil.set(tokenKey, ShiroUtils.getUser(),60*60*24);
			List<Tree<MenuDO>> menus = menuService.listMenuVueTree(getUserId());
			List<MenuModel> list = new ArrayList<>();
			MenuVueUtils.copyNewMenuObject(list,menus);
			UserDO user = ShiroUtils.getUser();
			return R.ok().put("token",tokenKey).put("l",list).put("merchantId", user.getMerchantId());
		} catch (AuthenticationException e) {
			return R.error("用户或密码错误");
		}
	}

	@PostMapping("/user/info")
	@ResponseBody
	R getUserInfo( HttpServletRequest request,HttpServletResponse response) {
		UserDO user =  ShiroUtils.getUser();
		List<Tree<MenuDO>> menus = menuService.listMenuVueTree(getUserId());
		List<MenuModel> list = new ArrayList<>();
		MenuVueUtils.copyNewMenuObject(list,menus);
		return R.ok().put("i", new ResultReBuild<UserDO>().toNewObj(user, new String[] {
				"name"
		})).put("l",list);
	}


	@RequestMapping("/user/menu")
	@ResponseBody
	R getUserMenu( HttpServletRequest request,HttpServletResponse response) {
		List<Tree<MenuDO>> menus = menuService.listMenuVueTree(getUserId());
		List<MenuModel> list = new ArrayList<>();
		MenuVueUtils.copyNewMenuObject(list,menus);
		return R.ok().put("l",list);
	}

	@RequestMapping("/user/menu/tree")
	@ResponseBody
	R getUserMenuTree( HttpServletRequest request,HttpServletResponse response) {
		List<Tree<MenuDO>> menus = menuService.listMenuVueTree(getUserId());
		return R.ok().put("l",menus);
	}

	@PostMapping("/user/perms")
	@ResponseBody
	R  getPerms(HttpServletRequest request,HttpServletResponse response) {
		Set<String> perms = menuService.listPerms(ShiroUtils.getUser().getUserId());
		Map map = new HashMap();
		for(String str : perms){
			map.put(str,true);
		}
		return R.ok().put("l",map);
	}



	@PostMapping("/user/logout")
	@ResponseBody
	R  userLogOut( HttpServletRequest request,HttpServletResponse response) {
		String ssoToken =  request.getParameter("sso_token");
		if(com.bootdo.common.utils.StringUtils.isEmpty(ssoToken)){
			ssoToken = request.getHeader("sso_token");
		}
		redisUtil.del(ssoToken);
		return R.ok("退出成功");
	}


	@PostMapping("/user/tuichu")
	@ResponseBody
	R  userTuichu( HttpServletRequest request,HttpServletResponse response) {
		String ssoToken =  request.getParameter("sso_token");
		if(com.bootdo.common.utils.StringUtils.isEmpty(ssoToken)){
			ssoToken = request.getHeader("sso_token");
		}
		redisUtil.del(ssoToken);
		return R.ok("退出成功");
	}



	@GetMapping("/logout")
	String logout(HttpServletRequest request,HttpServletResponse response) {
		ShiroUtils.logout();
		CookieUtils.setCookie("saveMe", "", response, 0);
		System.out.println("删除了cookie");
		return "redirect:/login";
	}






	@GetMapping("/main")
	String main() {
		return "main";
	}

}
